import axios from "axios";
import router from './../router'

import ElectronStore from 'electron-store'
export const localStore = new ElectronStore()
import {Message} from 'element-ui'
const service = axios.create()
axios.defaults.withCredentials = false
axios.defaults.timeout = 5000
function changeApiUrl(){
    let arr = localStore.get("apiurl_list");
    if(arr != null){
        let first = arr.shift();
        arr.push(first);
        localStore.set("apiurl_list",arr)
    }
}
service.interceptors.request.use(
    config=>{
        return config
    },
    error=>{// 请求超时
        Message({
            message:'网络请求失败、请稍后重试',
            type:'error',
            duration:5*1000
        })
        changeApiUrl()
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    res=>{
        if(res.status == 200 || res.status == 204){
            if(localStore.get("access_token") == null || (res.data.ret == 0 && res.data.msg =='token is null')){
                router.push({
                    path:'/login'
                })
            }
            return res
        }else{
            Message({
                message:res.message,
                type:'error',
                duration:5*1000
            })
            changeApiUrl()
            return Promise.resolve(res.message)
        }
    },
    error=>{
        Message({
            message:"服务器异常",
            type:'error',
            duration:3*1000
        })
        changeApiUrl()
        return Promise.resolve(error)
    }
)
export default service